from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QKeyEvent
from PySide6.QtWidgets import (QApplication, QListWidget, QWidget, QLabel, QStackedLayout,
                               QAbstractItemView, QStatusBar, QVBoxLayout)
# import cv2
# import pytesseract
from cnocr import CnOcr
from cnstd import CnStd

class Tab1(QWidget):
    def  __init__(self, parent=None):
        super().__init__(parent)
        self.tab1layout = QStackedLayout()
        self.t1 = QLabel(self)
        self.t1.setText("Drag in or right click to paste pictures in this window")
        self.tab_1 = ListWidget()
        self.tab1layout.addWidget(self.t1)
        self.tab1layout.addWidget(self.tab_1)
        self.setLayout(self.tab1layout)
        self.setAcceptDrops(True)
        # self.setStatusTip("Enter while pictures ready")
        self.statusBar = QStatusBar()
        self.statusBar.showMessage("Enter while pictures ready")
        self.tab_1.layout.addWidget(self.statusBar, 0, Qt.AlignBottom)
        self.tab_1.pastepictures.connect(self.mimedatahasurls)
        
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            print("invalid clipbord content")
            
    def picname(self, path):
        print(path)
        split = path.split("/")[-1]
        s1 = split.split(".")[1]
        if split not in self.tab_1.pic and (s1 == 'jpg' or s1 == 'png'):
            self.tab_1.path.append(path)
            self.tab_1.pic.append(split)
            self.tab_1.addItem(split)
        elif split in self.tab_1.pic:
            print("picture already added")
        elif s1 != 'jpg' or s1 != 'png':
            print('only support picture format')
            
    def dropEvent(self, event):
        urls = event.mimeData().urls()
        for url in urls:
            path = url.toLocalFile()
            self.picname(path)
        if self.tab1layout.currentWidget() == self.t1:
            self.tab1layout.setCurrentWidget(self.tab_1)
            self.update()
    
    def mimedatahasurls(self, mimedata):
        for i in mimedata.urls():
            url = i.toLocalFile()
            print(url)
            self.picname(url)
        if self.tab1layout.currentWidget() == self.t1:
            self.tab1layout.setCurrentWidget(self.tab_1)
            self.update()
                
    def mouseReleaseEvent(self, e):
        if e.button() == Qt.RightButton:
            clipboard = QApplication.clipboard()
            mimedata = clipboard.mimeData()
            if mimedata.hasUrls():
                self.mimedatahasurls(mimedata)
                        
class ListWidget(QListWidget):
    getalltext = Signal()
    currentab2 = Signal(str)
    pastepictures = Signal(object)
    def __init__(self, parent=None):
        super().__init__(parent=None)
        self.setAcceptDrops(True)
        self.dragEnabled()
        self.setDragDropMode(QAbstractItemView.InternalMove)
        self.cr = CnOcr(rec_vocab_fp="label_cn.txt")
        self.std = CnStd()
        self.pic = []
        self.path = []
        self.alltext = []
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.setToolTip("Double click to preview picture")
        self.itemDoubleClicked.connect(self.doubleclicked)
    
    def doubleclicked(self, item):
        text1 = item.text()
        for i in self.path:
            if text1 in i:
                print(f'open\t{text1}')
                self.currentab2.emit(i)
    
    def mouseReleaseEvent(self, e):
        if e.button() == Qt.RightButton:
            clipboard = QApplication.clipboard()
            mimedata = clipboard.mimeData()
            self.pastepictures.emit(mimedata)
        
    def orderpath(self):
        for i in range(self.count()):
            name = self.item(i).text()
            for j in range(len(self.path)):
                if name in self.path[j]:
                    if not j == i:
                        p1 = self.path[j]
                        self.path[j] = self.path[i]
                        self.path[i] = p1
    
    def foreverypic(self, info):
        upy = 0
        downy = 0
        t_t = ''
        for infos in info['detected_texts']:
            cropped_img = infos['cropped_img']
            box = infos['box']
            upoint = (box[0][1] + box[1][1]) / 2
            downpoint = (box[2][1] + box[3][1]) / 2
            upp = abs(upoint - upy)
            downn = abs(downpoint - downy)
            uplusdown = upp + downn
            ocr_res = self.cr.ocr_for_single_line(cropped_img)
            text = ocr_res['text']
            if (uplusdown < 10 
                or (upy < upoint and downy > downpoint) 
                or (upy > upoint and downy < downpoint)):
                t_t += '  ' + text
            else:
                t_t += '\n' + text  
            upy = upoint
            downy = downpoint
        self.alltext.append(t_t)
        
    def returnPressed(self):
        self.alltext.clear()
        self.orderpath()
        for i in self.path:
            info = self.std.detect(i)
            self.foreverypic(info)
        self.getalltext.emit()
            # text = self.cr.ocr(i)
            # for i in text:
            #     t_t += i.get('text') + '\n'
            # self.alltext.append(t_t)
            # img = cv2.imread(i)
            # cv2.imshow('img', img)
            # text = pytesseract.image_to_string(img)
            # print(text)
    def deletePressed(self):
        name = self.item(self.currentRow()).text()
        for i in self.path:
            if name in i:
                ph = i
                break
        self.path.remove(ph)
        self.pic.remove(name)
        self.takeItem(self.currentRow())
        print(f'delete {name}')
        
    def keyPressEvent(self, event:QKeyEvent):
        if event.key() == Qt.Key_Backspace:
            self.deletePressed()
        elif event.key() == Qt.Key_Return:
            self.returnPressed()
        
    